<template>
  <!-- 增加修改 -->
  <a-drawer width="60%" :label-col="4" :wrapper-col="14" :visible="open" @close="onClose">
    <a-divider orientation="left">
      <b>{{ formTitle }}</b>
    </a-divider>
    <a-form-model ref="form" :model="form" :rules="rules" :layout="'horizontal'" style="pointer-events: none;">

      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-model-item label="零件图号" prop="partDrawingNo">
            <!-- <SelectInput :options="inventoryItemList" :inputValue="''"/> -->
            <a-input v-model="form.partDrawingNo" placeholder="请输入" />
          </a-form-model-item>
        </a-col>

        <a-col
          :span="12">
          <!-- externalBatchNumber -->
          <a-form-model-item label="零件名称" prop="partName">
            <a-input v-model="form.partName" placeholder="请输入" />

          </a-form-model-item>
        </a-col>

      </a-row>
      <a-row :gutter="24">

        <a-col :span="12">
          <a-form-model-item label="版本号" prop="version">
            <a-input v-model="form.version" placeholder="请输入" />
          </a-form-model-item>
        </a-col>

        <a-col
          :span="12">
          <a-form-model-item label="登记日期" prop="createTime">
            <a-date-picker
              :value="form.createTime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="e=>handleChange(e, form, 'createTime')"
            />
          </a-form-model-item>
        </a-col>
      </a-row>

      <a-row :gutter="24">

        <a-col
          :span="12">
          <a-form-model-item label="是否涉密" prop="isSecret">
            <a-checkbox @change="(e)=>form.isSecret=e.target.checked?1:0" :value="form.isSecret">
              涉密
            </a-checkbox>
          </a-form-model-item>
        </a-col>

      </a-row>
      <a-divider />
      <!-- 交付节点 -->

      <a-row :gutter="24">
        <a-col :span="7">
          <a-row :gutter="24" style="font-weight: 600; font-size: 16px;">
            <a-space>
              <p>文档目录</p>
            </a-space>
          </a-row>
          <a-row>
            <a-col :span="24">
              <a-space>
                <a-button type="primary" class="editable-add-btn" @click="$refs.addProjectModal.showModal('新增同级', findNode(form.directoryList, projectModalId).parentId, type='t', projectModalNode)" size="small" :disabled="projectModalId===selectProjectId || !projectModalId">
                  新增同级
                </a-button>
                <a-button type="primary" class="editable-add-btn" @click="$refs.addProjectModal.showModal('新增下级', projectModalId, type='x', projectModalNode)" size="small" :disabled=" !projectModalId">
                  新增下级
                </a-button>
                <a-button type="danger" class="editable-add-btn" @click="deleteProjectModal(form.directoryList, projectModalId)" size="small" :disabled="projectModalId===selectProjectId || !projectModalId">
                  删除
                </a-button>
              </a-space>
            </a-col>
          </a-row>
          <CommonTree
            :treeOptions="form.directoryList"
            :replaceFields="{children: 'children', title: 'directoryName', key: 'id', value: 'id'}"
            @select="selectProjectDir"/>
        </a-col>
        <a-col :span="17">
          <a-row :gutter="24" style="font-weight: 600; font-size: 16px;">
            <a-space>
              <p>文档</p>
            </a-space>
          </a-row>
          <a-row :gutter="24" style="padding-bottom: 8px;">
            <a-col :span="24">
              <a-space>
                <a-button type="primary" class="editable-add-btn" @click="addWordInfo" size="small" :disabled="!projectModalId">
                  新增
                </a-button>
              </a-space>
            </a-col>
          </a-row>
          <a-row>
            <a-table bordered :data-source="projectModalNode.projectFileList" :columns="projectColumns" size="small" :pagination="false">

              <template slot="fileName" slot-scope="text, record">
                <a-input :value="text" @change="e=>handleChange(e.target.value, record, 'fileName')"/>
              </template>

              <template slot="versionNumber" slot-scope="text, record">
                <a-input :value="text" @change="e=>handleChange(e.target.value, record, 'versionNumber')"/>
              </template>

              <template slot="files" slot-scope="text, record">
                <!-- <a-input :value="text" @change="e=>handleChange(e.target.value, record, 'fileName')"/> -->

                <a-upload
                  name="file"
                  :multiple="true"
                  action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                  :headers="headers"
                  @change="e=>handleChange(e.target.value, record, 'fileName')"
                  :value="text"
                >
                  <a-button> <a-icon type="upload" /> 上传 </a-button>
                </a-upload>
              </template>

              <template slot="createTime" slot-scope="text, record">
                <a-date-picker
                  :value="text"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :show-time="{ defaultValue: dayjs('00:00:00', 'HH:mm:ss') }"
                  @change="e=>handleChange(e, record, 'createTime')"
                />
              </template>

              <!-- :show-time="{ defaultValue: dayjs('00:00:00', 'HH:mm:ss') }" -->
              <template slot="action" slot-scope="text, record">
                <a href="javascript:;" @click="handleDelete(record)" >删除</a>
              </template>
            </a-table>
          </a-row>

        </a-col>
      </a-row>

      <div class="bottom-control">
        <a-space>
          <a-button type="primary" :loading="submitLoading" @click="submitForm">
            保存
          </a-button>
          <a-button type="dashed" @click="cancel">
            取消
          </a-button>
        </a-space>
      </div>
    </a-form-model>

    <AddProjectModal ref="addProjectModal" @ok="addProject"/>
  </a-drawer>
</template>

<script>
import { partPlanIncomingPage } from '@/api/plan/incoming'
import { list as inventoryList } from '@/api/baseData/inventory'
import dayjs from 'dayjs'
import customParseFormat from 'dayjs/plugin/customParseFormat'
import SelectInput from '@/components/SelectInput'
import CommonTree from '@/components/CommonTree'
import AddProjectModal from './AddProjectModal'
import { add, getById, update } from '@/api/project/registration'

export default {
  name: 'CreateForm',
  props: {
    deptOptions: {
      type: Array,
      required: true
    }
  },
  components: {
    SelectInput,
    CommonTree,
    AddProjectModal
  },
  data () {
    dayjs.extend(customParseFormat)

    return {
      submitLoading: false,
      replaceFields: { children: 'children', title: 'batchNumber', key: 'id', value: 'id' },
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      formTitle: '',
      // 表单参数
      form: {
        partName: undefined,
        partDrawingNo: undefined,
        version: undefined,
        createTime: undefined,
        isSecret: undefined,
        directoryList: []
      },
      open: false,
      rules: {
        partDrawingNo: [
          { required: true, message: '零件图号不能为空', trigger: 'blur' }
        ],
        version: [
          { required: true, message: '版本号不能为空', trigger: 'blur' }
        ],
        partName: [
          { required: true, message: '零件名称不能为空', trigger: 'blur' }
        ],
        createTime: [
          { required: true, message: '登记日期不能为空', trigger: 'blur' }
        ]
      },
      projectColumns: [
      {
        title: '文档名称',
        dataIndex: 'fileName',
        scopedSlots: { customRender: 'fileName' },
        width: 80,
        align: 'center'
      },
        {
          title: '版本号',
          dataIndex: 'versionNumber',
          ellipsis: true,
          scopedSlots: { customRender: 'versionNumber' },
          width: 80
        },
        {
          title: '文件上传',
          dataIndex: 'files',
          scopedSlots: { customRender: 'files' },
          ellipsis: true,
          width: 80
        },
        {
          title: '上传日期',
          dataIndex: 'createTime',
          scopedSlots: { customRender: 'createTime' },
          ellipsis: true,
          width: 80
        },
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
          width: 50
        }

      ],
      partPlanIncomingList: [],
      inventoryItemList: [],
      nametestPieceEnum: [
        { label: '是', value: 1 },
        { label: '否', value: 0 }
      ],
      deptNodes: [],
      projectModalId: '',
      projectModalNode: [],
      selectProjectId: '',
      editEnable: false
    }
  },
  filters: {
  },
  created () {
    this.getPartPlanIncomingList()
    this.getinventoryItem()
  },
  computed: {
    // // 处理后的数据，拼接 name 和 code
    // processedTreeData () {
    //   const processData = (data) => {
    //     return this.inventoryItemList.map(item => ({
    //       title: `(${item.inventoryCode}|${item.inventoryName})`, // 拼接两个字段
    //       value: item.inventoryName,
    //       key: item.id,
    //       children: item.children ? processData(item.children) : undefined
    //     }))
    //   }
    //   return processData(this.rawTreeData)
    // }

  },
  watch: {
  },
  methods: {
    dayjs, // 将 dayjs 作为方法暴露给模板
    findNode (nodes, id) {
      const n = nodes.filter(item => item.id === id)[0]
      if (n !== undefined) {
        return n
      } else {
        for (const item of nodes) {
          if (item.children) {
            return this.findNode(item.children, id)
          }
        }
      }
    },
    // 添加文档目录
    addProject (node) {
      if (this.type === 'x') {
        this.projectModalNode.children.push(node)
      } else {
        this.findNode(this.form.directoryList, this.projectModalNode.parentId).children.push(node)
      }

      console.info(this.form.directoryList, 'ssssss')
    },
    // 选择文档目录
    selectProjectDir (projectId) {
      console.info('select', projectId)
      if (projectId) {
        this.projectModalId = projectId
        this.projectModalNode = this.findNode(this.form.directoryList, projectId)
      } else {
        this.projectModalId = undefined
        this.projectModalNode = {}
      }
    },
    // 删除文档目录
    deleteProjectModal (tree, id) {
      for (let i = 0; i < tree.length; i++) {
        const item = tree[i]
        if (item.id === id) {
          this.$delete(tree, i)
        } else {
          this.deleteProjectModal(item.children, id)
        }
      }
      this.form.directoryList = this.form.directoryList.filter(item => item.id !== this.projectModalId)
    },
    // 删除文档文件
    handleDelete (record) {
      this.projectModalNode.projectFileList = this.projectModalNode.projectFileList.filter(item => item.id !== record.id)
    },
    // 表格值响应
    handleChange (e, info, ee) {
      console.info(e, info, ee)
      info[ee] = e
    },
    // 选择外部批次号
    selectExternalBatchNumber (selectedKeys, info) {
      console.info((this.partPlanIncomingList.filter(it => it.id === selectedKeys)[0]))
      this.form.partDrawingNo = (this.partPlanIncomingList.filter(it => it.id === selectedKeys)[0]).partDrawingNo
      this.form.externalBatchNumber = (this.partPlanIncomingList.filter(it => it.id === selectedKeys)[0]).batchNumber
    },
    // 选择零件名称
    selectPartName (selectedKeys, info) {
      console.log('selected', selectedKeys, info, this.inventoryItemList.filter(it => it.inventoryName === selectedKeys)[0])
      this.form.partAbbreviation = (this.inventoryItemList.filter(it => it.inventoryName === selectedKeys)[0]).shortName
      this.form.unitOfMeasurement = (this.inventoryItemList.filter(it => it.inventoryName === selectedKeys)[0]).unitOfMeasurement
    },
    // 来料交付计划列表
    getPartPlanIncomingList () {
      partPlanIncomingPage({ pageSize: 100, pageNum: 1 }).then(res => {
        this.partPlanIncomingList = res.rows
      })
    },
    // 存货档案
    getinventoryItem () {
      inventoryList({}).then(res => {
        this.inventoryItemList = res.data
        console.info(this.inventoryItemList, 'ddd')
      })
    },
    onClose () {
      this.open = false
    },
    // 取消按钮
    cancel () {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset () {
      this.deptNodes = []
      this.form = {
        partName: undefined,
        partDrawingNo: undefined,
        version: undefined,
        createTime: undefined,
        isSecret: undefined,
        directoryList: []
      }
    },
    // 添加零件
    orderNodeList () {
      this.form.orderNodeList.push({
          nametestPiece: 0,
          partNumber: '',
          internalNumber: '',
          castingNumber: '',
          partName: this.form.partName

      })
    },
    addWordInfo () {
      console.info(this.projectModalNode, this.projectModalNode.projectFileList, '===>')
      this.projectModalNode.projectFileList.push(
        {
          id: new Date().getTime(),
          fileName: '',
          versionNumber: '',
          createTime: ''
      }

      )
    },
     /** 新增按钮操作 */
    handleAdd (selectProjectId) {
      if (!selectProjectId) {
        this.$message.error(
                '请先选择项目',
                3
              )
        return
      }
      this.reset()
      this.$emit('select-tree')
      this.open = true
      this.formTitle = '外来资料登记'
      this.selectProjectId = selectProjectId
      // this.form.directoryList = this.deptOptions.filter(item => item.id === selectProjectId).map(item => {
      //   return { children: [], directoryName: item.projectName, id: item.id }
      // })
      this.getAllDeptNode(this.deptOptions)
      console.info(this.form.directoryList, '4444', this.deptOptions, this.deptNodes)
      this.form = {
        partName: undefined,
        partDrawingNo: undefined,
        version: undefined,
        createTime: undefined,
        isSecret: undefined,
        projectId: selectProjectId,
        directoryList: this.deptNodes.filter(item => item.id === selectProjectId).map(item => {
          return { children: [], directoryName: item.projectName, id: item.id, projectFileList: [] }
        })
      }

    this.getinventoryItem()
      console.info(this.form.directoryList, '44424', this.deptOptions)
    },
    getAllDeptNode (nodes) {
      if (!nodes || nodes.length === 0) {
        return []
      }
      nodes.forEach(node => {
        this.deptNodes.push(node)
        return this.getAllDeptNode(node.children)
      })
    },
    /** 修改按钮操作 */
    handleUpdate (row, ids, editEnable = true) {
      this.reset()
      this.$emit('select-tree')
      getById(row.id).then((res) => {
        this.form = res.data
        this.open = true
        this.formTitle = '外来资料登记'
        this.selectProjectId = res.data.projectId
        this.editEnable = editEnable
      })
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.submitLoading = true
          if (this.form.id !== undefined) {
            this.form.directoryList = this.setIdIsNull(this.form.directoryList, 'id')
            update(this.form).then(response => {
              this.$message.success(
                '修改成功',
                3
              )
              this.open = false
              this.$emit('ok')
            }).finally(() => {
              this.submitLoading = false
            })
          } else {
            this.form.directoryList = this.setIdIsNull(this.form.directoryList, 'id')
            console.info('data,', this.form)
            add(this.form).then(response => {
              this.$message.success(
                '新增成功',
                3
              )
              this.open = false
              this.$emit('ok')
            }).finally(() => {
              this.reset()

              this.submitLoading = false
            })
          }
        } else {
          return false
        }
      })
    },
    setIdIsNull (data, key) {
      console.info(data, key, '===>')
      debugger
      if (data === null || data === undefined) {
        return null
      }
      data.forEach(item => {
        if (item[key]) {
          item[key] = undefined
        }
        if (item.children) {
          item.children = this.setIdIsNull(item.children, key)
        }
        if (item.projectFileList) {
          item.projectFileList = this.setIdIsNull(item.projectFileList, key)
        }
      })

      return data
    }
  }
}
</script>
